package com.example.blogother.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.blogother.mapper.UserinfoMapper;
import com.example.blogother.util.MessageUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xpd.blog.bean.Chat;
import com.xpd.blog.bean.Message;
import com.xpd.blog.bean.Userinfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@RestController
@ServerEndpoint("/chat/{id}")
public class ChatWebSocketController {


    //通过static关键字让userviceImpl变成静态变量属于WebSocketServer类,后面所有的WebSocketServer类的对象共享此变量
    private static UserinfoMapper userinfoMapper;

    @Autowired //将userviceImpl注入到WebSocketServer类的静态变量userviceImpl里
    public void setUserinfoMapper(UserinfoMapper userinfoMapper) {
        ChatWebSocketController.userinfoMapper = userinfoMapper;
    }
    //用来存储每一个客户端对应的ChatController对象
   private static Map<String,ChatWebSocketController> onlines=new ConcurrentHashMap<>();
   //声明一个session对象，用来指定发送消息给指定的用户
   private Session session;
   private Userinfo userinfo;

    @OnOpen
    public void Onopen(Session session, EndpointConfig config,@PathParam("id") String id){
     //将局部的session复制个成员session
     this.session=session;
        System.out.println("id = " + id);
        LambdaQueryWrapper<Userinfo> lqw=new LambdaQueryWrapper<>();
        userinfo = userinfoMapper.selectByUsidAfter(Integer.parseInt(id));
        onlines.put(userinfo.getUname(),this);
        String message = MessageUtil.getMessage(true, null, getNames());
        broadAllUser(message);
    }
    private void broadAllUser(String message){
        Set<String> strings = onlines.keySet();
        for (String string : strings) {
            System.out.println("string = " + string);
            ChatWebSocketController chatController = onlines.get(string);
            System.out.println("chatController.getNames() = " + chatController.getNames());
            try {
                chatController.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  private Set<String> getNames(){
     return onlines.keySet();
    }
    @OnClose
    public void Onclose(Session session){


    }
    @OnMessage
    public void OnMessaga(String message,Session session) throws IOException {
        Userinfo userinfo1 ;
        System.out.println("message = " + message);
        ObjectMapper objectMapper=new ObjectMapper();
        Chat chat = objectMapper.readValue(message, Chat.class);
        userinfo1=  userinfoMapper.selectByUsidAfter(chat.getUsid());
        String resultMessage = MessageUtil.getMessage(false, userinfo1.getUname(), chat.getContent());
        //判断会话有没有关闭
        System.out.println("session.isOpen() = " + session.isOpen());
        if (session.isOpen()) {
            try {
                onlines.get(userinfo1.getUname()).session.getBasicRemote().sendText(resultMessage);
                userinfo1= userinfoMapper.selectByUsidAfter(chat.getUid());
                onlines.get(userinfo1.getUname()).session.getBasicRemote().sendText(resultMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            // 处理会话已关闭的情况，例如记录日志或抛出异常
            userinfo1= userinfoMapper.selectByUsidAfter(chat.getUid());
            onlines.get(userinfo1.getUname()).session.getBasicRemote().sendText(resultMessage);
        }


    }


}
